package ecustom.finance.actions;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import ecustom.common.AbstractAction;
import ecustom.common.conn.DB;
import ecustom.common.util.CustomUtil;
import ecustom.finance.bean.PushPayableBean;
import ecustom.finance.bean.SaveFYFKDBean;
import ecustom.finance.bean.SavePayableBean;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

/**
* @author 作者:Gcc
* @createDate 创建时间：Aug 14, 2023 11:48:43 PM
* 
*/
public class FYLFKAction extends AbstractAction{
	
	protected static final Logger log = Logger.getLogger(AbstractAction.class); 

	@Override
	public void process(RequestInfo requestInfo) throws Exception {
		Property[] mainFields = requestInfo.getMainTableInfo().getProperty();
		
		if(super.getMainInteger(mainFields, "sftserp") == 1) return;	// 是否推送ERP：0:是；否：1
		if(CustomUtil.isNotBlank(super.getMainString(mainFields, "erpNumber"))) return;	// ERP编码为空的情况，不重复推送给ERP
		
		Integer zd = super.getMainIntegerCK(mainFields, "zd", "制单不能为空！");	// 所属公司
		Map<String, Object> erpResult = new HashMap<String, Object>();
		if(zd == 0) {	// 期末金蝶存在计提	费用类付款单（流程中会填写计提的应付单号）	下推-应付单-费用应付单	流程中的应付单号不为空的时候，调用下推应付单接口
			PushPayableBean ben = new PushPayableBean();
			erpResult = ben.handlERPData(requestInfo, mainFields);
		}else if(zd == 1) {	// 预付款	费用类付款单	创建-付款单-费用付款单
			SaveFYFKDBean bean = new SaveFYFKDBean();
			erpResult = bean.handlERPData(requestInfo, mainFields);
		}else if(zd == 2) {	// 除以上	费用类付款单	创建-应付单-费用应付单
			SavePayableBean bean = new SavePayableBean();
			erpResult = bean.handlERPData(requestInfo, mainFields);
		}else {
			throw new RuntimeException("其他类型制单不支持！请联系管理员！");
		}
		
		if(CustomUtil.isBlank(erpResult)) throw new RuntimeException("ERP返回内容为空！请联系管理员！");
		
		Integer requestId = requestInfo.getRequestManager().getRequestid();
		int formId = requestInfo.getRequestManager().getFormid();
		updateTable(formId, requestId, erpResult);
	}
	
	private int updateTable(Integer formId, Integer requestId, Map<String, Object> erpResult) throws SQLException {
		Integer erpFID = CustomUtil.getInteger(erpResult.get("FID"));
		String erpNumber = CustomUtil.getString(erpResult.get("Number"));
		String tableName = "FORMTABLE_MAIN_" + Math.abs(formId);
		String updateSql = "UPDATE "+tableName+" SET K3FID=?, ERPNUMBER=? WHERE REQUESTID=?";
		int i = DB.conn().executeUpdate(updateSql, erpFID, erpNumber, requestId);
		return i;
	}

}
